package com.gitee.srurl.system.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.gitee.srurl.core.annotation.Login;
import com.gitee.srurl.core.domain.SucUrlRecordDomain;
import com.gitee.srurl.core.dto.result.ShortUrlResultDTO;
import com.gitee.srurl.core.service.ISucUrlRecordService;
import com.gitee.srurl.core.util.PageQuery;
import com.gitee.srurl.core.util.valid.AddGroup;
import com.gitee.srurl.core.util.valid.UpdateGroup;
import com.gitee.srurl.system.biz.OpenApiBiz;
import com.gitee.srurl.core.cache.record.ShortUrlCacheManager;
import com.gitee.srurl.system.params.GenerateShortUrlParams;
import com.gitee.srurl.system.util.PageUtil;
import com.gitee.srurl.system.util.response.PageResponse;
import com.gitee.srurl.system.util.response.R;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * @author zxw
 * @date 2023/5/3 11:41
 */
@RestController
@RequestMapping("url_record")
@RequiredArgsConstructor
public class UrlRecordController {

    private final ISucUrlRecordService urlRecordService;

    private final OpenApiBiz openApiBiz;

    @Login
    @GetMapping("list")
    public R<PageResponse<SucUrlRecordDomain>> list(PageQuery pageQuery, SucUrlRecordDomain urlRecordDomain) {

        IPage<SucUrlRecordDomain> page = urlRecordService.getList(pageQuery, urlRecordDomain);
        return R.page(PageUtil.mybatisPageTransfer(page));
    }

    @Login
    @PostMapping
    public R<Void> add(@RequestBody @Validated(AddGroup.class) SucUrlRecordDomain urlRecordDomain) {

        GenerateShortUrlParams shortUrlParams = new GenerateShortUrlParams();
        shortUrlParams.setUrl(urlRecordDomain.getOriginUrl());
        shortUrlParams.setTimes(urlRecordDomain.getTimes());
        shortUrlParams.setExpireTime(urlRecordDomain.getExpireTime());
        ShortUrlResultDTO shortUrl = openApiBiz.getShortUrl(shortUrlParams);
        urlRecordService.add(urlRecordDomain, shortUrl);
        return R.ok();
    }

    @Login
    @PutMapping
    public R<Void> update(@RequestBody @Validated(UpdateGroup.class) SucUrlRecordDomain urlRecordDomain) {

        GenerateShortUrlParams shortUrlParams = new GenerateShortUrlParams();
        shortUrlParams.setUrl(urlRecordDomain.getOriginUrl());
        shortUrlParams.setTimes(urlRecordDomain.getTimes());
        shortUrlParams.setExpireTime(urlRecordDomain.getExpireTime());
        shortUrlParams.setUpdateTimes(urlRecordDomain.getUpdateTimes());
        ShortUrlResultDTO shortUrl = openApiBiz.getShortUrl(shortUrlParams);
        urlRecordService.updateUrlRecord(urlRecordDomain, shortUrl);
        return R.ok();
    }

    @Login
    @PutMapping("disabledOrActive/{id}")
    public R<Void> disabledOrActive(@PathVariable Long id) {

        urlRecordService.disabledOrActive(id);
        return R.ok();
    }
}
